package org.springside.examples.miniservice.ws.user;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Required;
import org.springside.examples.miniservice.entity.user.User;
import org.springside.examples.miniservice.service.user.UserManager;
import org.springside.examples.miniservice.ws.Constants;
import org.springside.examples.miniservice.ws.user.dto.UserDTO;
import org.springside.modules.webservice.FaultException;
import org.springside.modules.webservice.WebServiceSupport;

/**
 * WebService实现类.
 * 
 * 使用@WebService指向Interface定义类即可.
 * 
 * @author sky
 * @author calvin
 */
@WebService(endpointInterface = "org.springside.examples.miniservice.ws.user.UserWebService", targetNamespace = Constants.NS)
public class UserWebServiceImpl extends WebServiceSupport implements UserWebService {

	private UserManager userManager;

	/**
	 * @see UserWebService#getUser(Integer)
	 */
	public UserDTO getUser(Integer userId) throws FaultException {

		if (userId == null)
			throw new FaultException(Constants.PARAMETER_ERROR, "userId为空");

		// 获取User
		User userEnity = userManager.getUser(userId);
		if (userEnity == null) {
			logger.error("帐号ID：{}不存在", userId);
			throw new FaultException(Constants.FETCH_DATA_ERROR, "帐号ID" + userId + "不存在");
		}
		// 从User转换到UserDTO
		try {
			return (UserDTO) dozer.map(userEnity, UserDTO.class);
		} catch (Exception e) {
			logger.error("dozer转换错误", e);
			throw new FaultException(Constants.DATA_TRANSLATE_ERROR, "");
		}
	}

	/**
	 * @see UserWebService#createUser(UserDTO)
	 */
	public Integer createUser(UserDTO user) throws FaultException {

		if (user == null)
			throw new FaultException(Constants.PARAMETER_ERROR, "user为空");
		// 从DTO转换到User
		User userEntity = null;
		try {
			userEntity = (User) dozer.map(user, User.class);
		} catch (Exception e) {
			logger.error("dozer转换错误", e);
			throw new FaultException(Constants.DATA_TRANSLATE_ERROR, "");
		}
		// 保存User
		try {
			userManager.createUser(userEntity);
			return userEntity.getId();
		} catch (Exception e) {
			logger.error("保存帐号失败", e);
			throw new FaultException(Constants.SAVE_DATA_ERROR, "帐号保存失败");
		}
	}

	/**
	 * @see UserWebService#authUser(String, String)
	 */
	public Boolean authUser(String loginName, String password) {
		return userManager.auth(loginName, password);
	}

	@Required
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
}
